package top.broncho.lottery.ui.main

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.design.snackbar
import org.jetbrains.anko.info
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import top.broncho.lottery.R
import top.broncho.lottery.databinding.ActivityMainBinding
import top.broncho.lottery.ui.base.BaseDiActivity
import top.broncho.lottery.ui.history.HistoryActivity
import top.broncho.lottery.ui.ocr.OcrActivity
import top.broncho.lottery.ui.widget.SimpleListDividerDecorator
import top.broncho.lottery.util.clickWithTrigger
import java.text.SimpleDateFormat
import java.util.*

private const val REQUEST_ID = 99

class MainActivity : BaseDiActivity<MainViewModule, ActivityMainBinding>() {

    override fun isDisplayHomeAsUpEnabled() = false

    override fun getLayoutId() = R.layout.activity_main

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding?.lifecycleOwner = this
        binding?.vm = viewModule

        setSupportActionBar(appbar_layout_toolbar)
        val adapter = MainAdapter { lottery ->
            val lotteryDate = "20${lottery.lotteryDate} 21:30:00"
            info { "lotteryDate = $lotteryDate" }
            val sdf = SimpleDateFormat("yyyy-MM-DD HH:mm:ss", Locale.CHINESE)
            val date = sdf.parse(lotteryDate).takeIf { it != null } ?: Date()
            info { "$lotteryDate ${date.time} ${System.currentTimeMillis()}" }
            if (date.time > System.currentTimeMillis()) {
                binding?.root?.snackbar("暂未开奖")
            } else {
                viewModule.parseLottery(lottery)
            }
        }
        binding?.recyclerView?.adapter = adapter
        binding?.recyclerView?.addItemDecoration(
            SimpleListDividerDecorator(
                ContextCompat
                    .getDrawable(
                        applicationContext,
                        R.drawable.list_divider_h
                    ), null, false
            )
        )
        viewModule.getAllLotteries().observe(this, Observer {
            adapter.submitList(it)
        })

        binding?.addBtn?.clickWithTrigger {
            startActivityForResult<OcrActivity>(REQUEST_ID)
        }

        viewModule.prizeResult.observe(this, Observer { result ->
            if (result == null) {
                return@Observer
            }
            if (result.throwable != null) {
                binding?.root?.snackbar(result.throwable.message.toString())
                return@Observer
            }
            val prizeList = result.result
            if (prizeList.isNullOrEmpty()) {
                alert("下次继续努力噢!", "很遗憾，您没有中奖") {
                    positiveButton("好吧") { viewModule.prizeResult.postValue(null) }
                }.show()
            } else {
                val message: StringBuilder = StringBuilder()
                prizeList.forEach {
                    message.append(it.title)
                    message.append("：")
                    message.append(it.count)
                    message.append("注，")
                    message.append(" 奖金：")
                    message.append(it.amount * it.count)
                    message.append("元。")
                    message.append("\r\n")
                }
                alert(message, "恭喜您中奖了") {
                    positiveButton("欧也～") {
                        viewModule.prizeResult.postValue(
                            null
                        )
                    }
                }.show()
            }
        })
        viewModule.latestLottery.observe(this, Observer {
            info { "latestLottery: ${it.result}" }
            if (it.throwable != null) {
                binding?.root?.snackbar(it.throwable.message.toString())
                return@Observer
            }
//            binding?.lottery = it.result
//            binding?.balls = it.result?.lottery_res?.split(",")
//            binding?.numbers = it.result?.lottery_prize?.map { prize ->
//                prize.prize_num
//            }
//            binding?.amounts = it.result?.lottery_prize?.map { prize ->
//                prize.prize_amount
//            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ID && resultCode == Activity.RESULT_OK) {
            //ignore
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_history -> startActivity<HistoryActivity>()
        }
        return super.onOptionsItemSelected(item)
    }
}